//
//  394. 字符串解码.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/9/13.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution394 {
    func decodeString(_ s: String) -> String {
        let array: [Character] = Array(s)
        var stackNum: [Int] = []
        var stackStr: [String] = []
        var muti = 0
        for c in array {
            if c.isWholeNumber {
                muti = muti * 10 + c.wholeNumberValue!
            } else if c == "[" {
                stackNum.append(muti)
                muti = 0
                stackStr.append(String(c))
            } else if c == "]" {
                var subArray: [String] = []
                while !stackStr.isEmpty && stackStr.last != "["{
                    subArray.insert(stackStr.removeLast(), at: 0)
                }
                // 左括号出栈
                stackStr.removeLast()
                let subCount = stackNum.removeLast()
                for _ in 0..<subCount {
                    stackStr.append(contentsOf: subArray)
                }
            } else {
                stackStr.append(String(c))
            }
        }
        return stackStr.joined()
    }
    static func test() {
        let solution = Solution394()
//        let s = "3[a]2[bc]"
//        let s = "3[a2[c]]"
//        let s = "2[abc]3[cd]ef"
        let s = "abc3[cd]xyz"
        let result = solution.decodeString(s)
        print(result)
    }
}
